const path = require('path');
const fs = require('fs');
const glob = require('fast-glob');
const HtmlWebpackPlugin = require('html-webpack-plugin');
const CopyWebpackPlugin = require('copy-webpack-plugin');

const plugins = [];
const entry = {};

const exampleFilenamePrefix = process.env.DEV_SERVER ? 'examples/' : '';

const splitter = /.*\/(.*)\.html/;
for (const filename of glob.sync('examples/*.html', {onlyFiles: true})) {
  const matches = filename.match(splitter);
  const name = matches[1];
  const jsName = `./examples/${name}.js`;
  if (!fs.existsSync(jsName)) {
    continue;
  }
  entry[name] = [
    jsName
  ];

  plugins.push(
      new HtmlWebpackPlugin({
        template: `examples/${name}.html`,
        filename: `${exampleFilenamePrefix + name}.html`,
        chunks: ['commons', name],
      })
  );
}

// move data folder
plugins.push(new CopyWebpackPlugin({
  patterns: [
    {
      from: 'examples/data',
      to: 'data/',
    },
  ],
}));

const config = {
  entry,
  optimization: {
    splitChunks: {
      chunks: 'all',
      name: 'commons',
    }
  },
  plugins,
  // 加强 externals 配置
  externals: {
    'cesium': 'Cesium',
    'cesium/Source/Cesium': 'Cesium'
  }
};

if (!process.env.DEV_SERVER) {
  config.output = {
    path: path.resolve(__dirname, '../dist/examples/'),
  };
}

module.exports = config;
